from msgparser import readEmail
from imap import mainImap
from database import dbInsert, lastDate

import logging
logging.basicConfig(level=logging.DEBUG)

def read(file):
    f = open(file, 'r')
    s = f.read()
    f.close()
    ret = readEmail(s)
    return ret

def dataimport(date):
    files = mainImap(date)
    for f in files:
        msg = read(f)
        logging.info('inserting>' + msg.msg)
        dbInsert(msg)

if __name__ == '__main__':
    date = lastDate()
    from datetime import timedelta, datetime
    if date + timedelta(27) < date.today():
        logging.info('importing')
        dataimport(date)
    else:
        logging.info('not importing')